package strcut_to_map

import (
	"reflect"
	"time"
)

const TimeFormat = "2006-01-02 15:04:05"

func StructToMapWithNoEmpty(obj interface{}) map[string]interface{} {
	objValue := reflect.ValueOf(obj)
	objType := reflect.TypeOf(obj)
	objMap := make(map[string]interface{})
	for i := 0; i < objValue.NumField(); i++ {
		field := objType.Field(i)
		tag := field.Tag.Get("json")
		if tag == "" {
			tag = field.Name
		}
		// 时间格式的特殊处理与默认值处理
		if objValue.Field(i).IsZero() {
			continue
		}
		if field.Type.Name() == "Time" {

			objMap[tag] = (objValue.Field(i).Interface().(time.Time)).Format(TimeFormat)
		} else {
			objMap[tag] = objValue.Field(i).Interface()
		}
	}
	for k, v := range objMap {
		if v == "" {
			delete(objMap, k)
		}
	}
	return objMap
}

func StructToMapWithEmpty(obj interface{}) map[string]interface{} {
	objValue := reflect.ValueOf(obj)
	objType := reflect.TypeOf(obj)
	objMap := make(map[string]interface{})
	for i := 0; i < objValue.NumField(); i++ {
		field := objType.Field(i)
		tag := field.Tag.Get("json")
		if tag == "" {
			tag = field.Name
		}
		if field.Type.Name() == "Time" {
			objMap[tag] = (objValue.Field(i).Interface().(time.Time)).Format(TimeFormat)
		} else {
			objMap[tag] = objValue.Field(i).Interface()
		}
	}
	return objMap
}
